/*
 * @Author: viivLgr 
 * @Date: 2018-06-06 14:41:35 
 * @Last Modified by: viivLgr
 * @Last Modified time: 2018-06-07 15:59:09
 */
import React from 'react';

import PageTitle from 'component/page-title/index.jsx';
import CategorySelector from './category-selector.jsx';
import FileUploader from 'util/file-uploader/index.jsx';
import RichEditor from 'util/rich-editor/index.jsx';

import Product from 'service/product-service.jsx';
import Util from 'util/util.jsx';

import './save.scss';

const _product = new Product();
const _util = new Util();

class ProductSave extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: this.props.match.params.pid,
            name: '',
            subtitle: '',
            categoryId: 0,
            parentCategoryId: 0,
            subImages: [],
            price: '',
            stock: '',
            detail: '',
            status: 1 // 商品状态1为在售
        }
    }
    componentDidMount() {
        this.loadProduct();
    }
    // 加载详情
    loadProduct() {
        console.log(this.state.id);
        if (this.state.id) {
            // 编辑功能，需要表单回填
            _product.getProduct(this.state.id).then(res => {
                let images = res.subImages.split(',');
                res.subImages = images.map((imgUri, index) => {
                    return {
                        uri: imgUri,
                        url: res.imageHost + imgUri
                    }
                });
                res.defauleDetail = res.detail;
                this.setState(res);
            }, errMsg => {
                _util.errorTips(errMsg);
            });
        }
    }
    // 简单字段的改变，商品名称、描述、价格、库存
    onValueChange(e) {
        let name = e.target.name,
            value = e.target.value.trim();
        this.setState({
            [name]: value
        });
    }
    // 品类选择器的变化
    onCategoryChange(categoryId, parentCategoryId) {
        this.setState({
            categoryId: categoryId,
            parentCategoryId: parentCategoryId
        });
    }
    // 上传图片成功
    onUploadSuccess(res) {
        let subImages = this.state.subImages;
        subImages.push(res);
        this.setState({
            subImages: subImages
        });
    }
    // 上传图片失败
    onUploadError(errMsg) {
        _util.errorTips(errMsg);
    }
    // 删除图片
    onImageDelete(e) {
        let index = +e.target.dataset.index,
            subImages = this.state.subImages;
        subImages.splice(index, 1);
        this.setState({
            subImages: subImages
        });
    }
    // 富文本编辑器的变化
    onDetailValueChange(value) {
        this.setState({
            detail: value
        });
    }
    getSubImagesString() {
        return this.state.subImages.map(item => item.uri).join(',');
    }
    // 提交表单
    onSubmit() {
        let product = {
            name: this.state.name,
            subtitle: this.state.subtitle,
            categoryId: parseInt(this.state.categoryId),
            subImages: this.getSubImagesString(),
            detail: this.state.detail,
            price: parseFloat(this.state.price),
            stock: parseInt(this.state.stock),
            status: this.state.status
        },
            productCheckResult = _product.checkProduct(product);
        if (this.state.id) {
            product.id = this.state.id;
        }
        if (productCheckResult.status) {
            // 表单验证成功
            _product.saveProduct(product).then(res => {
                _util.successTips(res);
                this.props.history.push('/product/index');
            }, errMsg => {
                _util.errorTips(errMsg);
            });
        } else {
            // 表单验证失败
            _util.errorTips(productCheckResult.msg);
        }
    }
    render() {
        return (
            <div id="page-wrapper">
                <PageTitle title={this.state.id ? '编辑商品' : '添加商品'} />
                <div className="form-horizontal">
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品名称</label>
                        <div className="col-md-5">
                            <input type="text" className="form-control" placeholder="请输入商品名称"
                                value={this.state.name}
                                name="name"
                                onChange={(e) => this.onValueChange(e)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品描述</label>
                        <div className="col-md-5">
                            <input type="text" className="form-control" placeholder="请输入商品描述"
                                value={this.state.subtitle}
                                name="subtitle"
                                onChange={(e) => this.onValueChange(e)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">所属分类</label>
                        <CategorySelector
                            categoryId={this.state.categoryId}
                            parentCategoryId={this.state.parentCategoryId}
                            onCategoryChange={(categoryId, parentCategoryId) => this.onCategoryChange(categoryId, parentCategoryId)
                            }
                        />
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品价格</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="number" className="form-control" placeholder="价格"
                                    value={this.state.price}
                                    name="price"
                                    onChange={(e) => this.onValueChange(e)}
                                />
                                <span className="input-group-addon">元</span>
                            </div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品库存</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="number" className="form-control" placeholder="库存"
                                    value={this.state.stock}
                                    name="stock"
                                    onChange={(e) => this.onValueChange(e)}
                                />
                                <span className="input-group-addon">件</span>
                            </div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品图片</label>
                        <div className="col-md-10">
                            {
                                this.state.subImages.length ? this.state.subImages.map((item, index) => (
                                    <div className="img-con" key={index}>
                                        <img src={item.url} />
                                        <i className="fa fa-close" data-index={index} onClick={(e) => this.onImageDelete(e)}></i>
                                    </div>
                                )) : (<div>请上传图片</div>)
                            }
                        </div>
                        <div className="col-md-offset-2 col-md-10">
                            <FileUploader
                                onSuccess={(res) => this.onUploadSuccess(res)}
                                onError={(err) => this.onUploadError(err)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品详情</label>
                        <div className="col-md-10">
                            <RichEditor
                                detail={this.state.detail}
                                defauleDetail={this.state.defauleDetail}
                                onValueChange={(value) => this.onDetailValueChange(value)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-md-offset-2 col-md-10">
                            <button className="btn btn-primary" onClick={(e) => this.onSubmit(e)}>提交</button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default ProductSave;